#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
<%= lines(autogen_notice(:python, pwd)) -%>

from __future__ import absolute_import, division, print_function
__metaclass__ = type

################################################################################
# Documentation
################################################################################

<%
  metadata_version = quote_string("1.1")
  supported_by = quote_string("community")

  uri_props = uri_properties_raw(object).reject { |para| para.nil? || para.name == 'name' }
-%>
ANSIBLE_METADATA = {'metadata_version': <%= metadata_version -%>,
                    'status': ["preview"],
                    'supported_by': <%= supported_by -%>}

DOCUMENTATION = '''
---
<%= ansible_style_yaml({
  'module' => "#{module_name(object)}_info",
  'description' => ["Gather info for GCP #{object.name}"],
  'short_description' => "Gather info for GCP #{object.name}",
  'author' => "Google Inc. (@googlecloudplatform)",
  'requirements' => ["python >= 2.6", "requests >= 2.18.4", "google-auth >= 1.3.0"],
  'options' => [
    ({
      object.facts.filter.name.underscore => {
        'description' => format_description(object.facts.filter.description),
        'type' => python_type(object.facts.filter),
        'elements' => ('str' if python_type(object.facts.filter) == 'list')
      }
    } if object.facts.has_filters),
    uri_props.map { |p| documentation_for_property(p) },
    auth_docs
  ].flatten.compact.reduce({}, :merge),
  'notes' => auth_notes
})-%>
'''

<% if example and example.facts -%>
EXAMPLES = '''
<%= lines(example.facts.build_example('facts', object)) -%>
'''
<% end -%>

RETURN = '''
<%= ansible_style_yaml({
  'resources' => {
    'description' => 'List of resources',
    'returned' => 'always',
    'type' => 'complex',
    'contains' => object.all_user_properties.map { |p| returns_for_property(p) }.reduce({}, :merge)
  }
})-%>
'''

################################################################################
# Imports
################################################################################
<%
  import = 'from ansible_collections.google.cloud.plugins.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest'
  import += ', replace_resource_dict' unless uri_props.select { |p| p.is_a?(Api::Type::ResourceRef) && !p.resource_ref.readonly }.empty?
-%>
<%= lines(import) -%>
import json

################################################################################
# Main
################################################################################


def main():
<%
  mod_props = object.facts.has_filters ? [object.facts.filter] : []
  mod_props += uri_props
-%>
    module = GcpModule(
<%=
  indent(remove_outside_dict(python_literal({
    'argument_spec'=> ansible_module(mod_props),
  })), 12)
-%>
    )

    if not module.params['scopes']:
        module.params['scopes'] = <%= python_literal(object.__product.scopes) %>

<%
  query_param = nil
  if object.facts.has_filters
    if object.facts.query_options
      query_param = "query_options(module.params['#{object.facts.filter.name}'])"
    else
      query_param = "module.params['#{object.facts.filter.name.underscore}']"
    end
  end
-%>
    return_value = {
        'resources': <%= method_call('fetch_list', ['module', 'collection(module)', query_param]) %>
    }
    module.exit_json(**return_value)


<%= lines(emit_link('collection', build_url(object.collection_url), object)) -%>


<%= method_decl('fetch_list', ['module', 'link', ('query' if object.facts.has_filters)]) %>
<% prod_name = object.__product.api_name -%>
    auth = GcpSession(module, <%= quote_string(prod_name) -%>)
    return <%= method_call('auth.list', ['link', "return_if_object", "array_name='#{object.collection_url_key}'", ("params={'#{object.facts.filter_api_param}': query}" if object.facts.has_filters)]) %>


<% if object.facts.has_filters && object.facts.query_options -%>
def query_options(filters):
    if not filters:
        return ''

    if len(filters) == 1:
        return filters[0]
    else:
        queries = []
        for f in filters:
            # For multiple queries, all queries should have ()
            if f[0] != '(' and f[-1] != ')':
                queries.append("(%s)" % ''.join(f))
            else:
                queries.append(f)

        return ' '.join(queries)


<% end -%>
<%=
  lines(method_decl('return_if_object', ['module', 'response']))
-%>
    # If not found, return nothing.
    if response.status_code == 404:
        return None

    # If no content, return nothing.
    if response.status_code == 204:
        return None

    try:
        module.raise_for_status(response)
        result = response.json()
    except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
        module.fail_json(msg="Invalid JSON response with error: %s" % inst)

    if navigate_hash(result, ['error', 'errors']):
        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))

    return result


if __name__ == "__main__":
    main()
